package com.ys.controller.api.storage;

import com.ys.config.MenuId;
import com.ys.entity.storage.TccDisassembleByHand;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccDisassembleByHandService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 手工拆装单
 */
@Controller
@RequestMapping("/api/inter/tccDisassembleByHand")
public class ApiInterTccDisassembleByHandController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccDisassembleByHandController.class);

    @Autowired
    private CommonApiService<TccDisassembleByHand> commonApiService;

    @Autowired
    private TccDisassembleByHandService tccDisassembleByHandService;

    //菜单id
    private Long menuId = MenuId.TCC_DisassembleByHand;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccDisassembleByHand:view";
    private final String PERMISSIONS_ADD = "tccDisassembleByHand:add";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccDisassembleByHand setSeachSql(TccDisassembleByHand cond){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
                //.addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

                .addLeftJoin("TP_ProductActive B ON B.Code = A.ProductCode")//listing库
                .addField("B.Name AS productName")//商品名称

                .addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm")
                .addField("C.Vgsjc AS vgsjc")//运营公司简称

                .addLeftJoin("TCC_Location D ON D.Chw = A.Chw")//货位信息表
                .addField("D.Vhw AS vhw")//货位
                .addLeftJoin("TCC_WarehouseArea E ON E.Ckq = D.Ckq")//库区
                .addField("E.Vkq AS vkq")//库区
                .addLeftJoin("TCC_Warehouse F ON F.Cck = E.Cck")//仓库
                .addField("F.Vck AS vck")//仓库

                //子件信息
                .addLeftJoin("TCC_DisassembleByHandItem SA ON SA.Pbid = A.Bid")
                .addField("SA.SubCode AS subCode")//子件编码
                .addField("SA.SubBomNum AS subBomNum")//子件BOM数量
                .addField("SA.SubDisNum AS subDisNum")//子件拆装数量
                .addField("SA.StoreNum AS storeNum")//入库数量
                .addField("SA.SubChw AS subChw")//货位编码

                .addLeftJoin("TP_ProductActiveComponent SB ON SB.Code = SA.SubCode")//listing库子件信息
                .addField("SB.Name AS subName")//子件名称

                .addLeftJoin("TCC_Location SD ON SD.Chw = SA.SubChw")//货位信息表
                .addField("SD.Vhw AS subVhw")//货位
                .addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
                .addField("SE.Vkq AS subVkq")//库区
                .addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
                .addField("SF.Vck AS subVck")//仓库

                //排序
        .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccDisassembleByHand cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccDisassembleByHand cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccDisassembleByHand> util = new ExportExcelUtils<>(new TccDisassembleByHand());
            String toFilePath = util.exportExcel(listData, listField, "手工拆装单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tccDisassembleByHandService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tccDisassembleByHandService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tccDisassembleByHandService.del(id);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            TccDisassembleByHand entity = new TccDisassembleByHand().setId(id).queryFirst();
            return tccDisassembleByHandService.flowPass(entity.getBid(), ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TccDisassembleByHand entity = new TccDisassembleByHand().setId(id).queryFirst();
            return tccDisassembleByHandService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TccDisassembleByHand entity = new TccDisassembleByHand().setId(id).queryFirst();
            return tccDisassembleByHandService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



}